package com.wtf.generator.executor;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.annotation.DbType;
import com.wtf.generator.config.DynamicDataSourceConfigProvide;
import com.wtf.generator.constants.DsDbStoreConstant;
import com.wtf.generator.entity.WtfDataSource;
import com.wtf.generator.model.dto.DsAddDTO;
import com.wtf.generator.service.WtfDataSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;
/**
 * date: 2022/6/18 10:59
 * @author linhuanyou
 * @email 496558736@qq.com
 * @version 1.0
 */
@Slf4j
@Component
public class DsInitExecutor extends AbstractExecutor implements InitializingBean {

    private static DefaultDataSourceCreator defaultDataSourceCreator ;

    private static WtfDataSourceService wtfDataSourceService;

    private static DynamicDataSourceConfigProvide dynamicDataSourceConfigProvide;

    private static DsDbExecutor dsDbExecutor;

    public static void doInit() {
        if(DsDbStoreConstant.isDsDbStore()){
            List<WtfDataSource> wtfDataSources = DsInitExecutor.wtfDataSourceService.list();
            for (WtfDataSource wtfDataSource : wtfDataSources) {
                DsAddDTO dsDbDTO = new DsAddDTO();
                BeanUtils.copyProperties(wtfDataSource,dsDbDTO);
                dsDbDTO.setDbType(DbType.getDbType(wtfDataSource.getDbType()));
                DataSourceProperty dataSourceProperty = dsDbExecutor.getDataSourceProperty(dsDbDTO);
                DataSource dataSource =  DsInitExecutor.defaultDataSourceCreator.createDataSource(dataSourceProperty);
                DynamicRoutingDataSource dynamicRoutingDataSource = dynamicDataSourceConfigProvide.getDynamicRoutingDataSource();
                dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(),dataSource);
                log.info("Load The Slave DataSource : {}",wtfDataSource);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DsInitExecutor.defaultDataSourceCreator = this.applicationContext.getBean(DefaultDataSourceCreator.class);
        DsInitExecutor.dynamicDataSourceConfigProvide = this.applicationContext.getBean(DynamicDataSourceConfigProvide.class);
        DsInitExecutor.wtfDataSourceService = this.applicationContext.getBean(WtfDataSourceService.class);
        DsInitExecutor.dsDbExecutor = this.applicationContext.getBean(DsDbExecutor.class);
    }

    @Override
    protected void initExecutors() {

    }
}
